import React, { Component } from 'react'
import { ImagePicker, WingBlank } from 'antd-mobile'
import api from '@MODULES/common/api'
import { Toast } from "antd-mobile/lib/index";

class UploadPic extends Component {
    constructor(props) {
        super(props)
        this.state = {
            requireImageCount: this.props.picCount || 1,
            imageFiles: [],
            imageFileChange: false,
        }

    }

    static getDerivedStateFromProps = (nextProps, prevState) => {
        if (nextProps.imageFiles && nextProps.imageFiles.length > 0 && !prevState.imageFileChange) {
            console.log('nextProps.imageFiles', nextProps.imageFiles)
            console.log('prevState.imageFiles', prevState)
            // return {imageFiles: nextProps.imageFiles}
            return { imageFiles: nextProps.imageFiles.map((i) => { return { url: i, src: i } }) }
        }
        return null
    }


    imagetoCanvas(image) {
        var cvs = document.createElement("canvas");
        var ctx = cvs.getContext('2d');
        cvs.width = image.width;
        cvs.height = image.height;
        ctx.drawImage(image, 0, 0, cvs.width, cvs.height);
        return cvs;
    }

    canvasResizetoFile(canvas, quality, mimeType, filename, fn) {
        canvas.toBlob(function (blob) {
            blob.name = filename + '.jpg'
            fn(blob);
        }, mimeType, quality);
    }

    filetoDataURL(file, fn) {
        var reader = new FileReader();
        reader.onloadend = function (e) {
            fn(e.target.result);
        };
        reader.readAsDataURL(file);
    }

    dataURItoBlob(dataURI) {
        // convert base64/URLEncoded data component to raw binary data held in a string
        let byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);

        // separate out the mime component
        let mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
        console.log('mimeString', mimeString)

        // write the bytes of the string to a typed array
        let ia = new Uint8Array(byteString.length);
        for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }

        return new Blob([ia], { type: mimeString });
    }

    dataURLtoImage(dataurl, fn) {
        var img = new Image();
        img.onload = function () {
            fn(img);
        };
        img.onerror = function () {
            Toast.fail('读取图片错误', 1)
        }
        img.src = dataurl;
    }

    fileResizetoFile(file, quality, mimeType, callback) {
        const that = this

        this.filetoDataURL(file, function (dataurl) {

            that.dataURLtoImage(dataurl, function (image) {
                let canvasImage = that.imagetoCanvas(image)
                console.warn(typeof (canvasImage.toBlob))
                if (typeof (canvasImage.toBlob) === 'function') {
                    that.canvasResizetoFile(canvasImage, quality, mimeType, file.name, callback);
                } else {
                    console.warn('uriToBlob')
                    let blobFile = that.dataURItoBlob(dataurl)
                    blobFile.name = file.name
                    callback(blobFile)
                }
            })
        })
    }


    onChange = (files, type, index) => {
        if (type === 'add') {
            let uploadFile = files[files.length - 1].file

            api.logger('upload', { change: type, name: uploadFile.name, size: uploadFile.size, type: uploadFile.type, lastModifiedDate: uploadFile.lastModifiedDate, })
            this.fileResizetoFile(uploadFile, 0.2, 'image/jpeg', (blobData) => {
                // api.logger('upload', {change: type, name: blobData.name, size: blobData.size, type: blobData.type,})
                api.uploadPic(blobData, this.props.uploadFileType || 'task', {
                    success: (res) => {
                        let data = res.data;
                        console.log('upload', data)
                        // api.logger('upload', {change: type+'success', src: data.imgURL})
                        files[files.length - 1].src = data.path;
                        files[files.length - 1].url = data.path;
                        console.warn('上传结果', files)
                        this.setState({
                            imageFiles: files,
                            imageFileChange: true,
                        }, () => {
                            this.handlePropsChange()
                        })

                    },
                    error: (e) => {
                        // Toast.fail('图片上传失败，请刷新重试！', 1.5)
                        // api.logger('upload', {change: type+'error', uploaderror: e.toString()})
                    }
                })

            })
        } else if (type === 'remove') {
            let files = this.state.imageFiles
            let removeFile = files.splice(index, 1)
            // api.logger('upload', {change: type, src: removeFile.src,})
            this.setState({ imageFiles: files, imageFileChange: true }, () => {
                this.handlePropsChange()
            });
        }
    }
    handleOnFail = (message) => {
        Toast.fail('图片选择失败，请刷新重试！', 1.5)
        // api.logger('upload', {failMsg: message})
        throw message
    }
    handlePropsChange = () => {
        // if (this.state.requireImageCount === this.state.imageFiles.length) {
        //   this.props.onChange(this.state.requireImageCount === 1 ? this.state.imageFiles[0].src : this.state.imageFiles.map((file) => { return file.src }))
        // } else {
        //   this.props.onChange(false, this.state.imageFiles.map((file) => { return file.src }))
        // }

        console.log('up.change', this.state.imageFiles)
        // this.props.onChange(this.state.imageFiles.map((file) => { return file.src }))
        // 1113 beifeng 调整使用url字段，url带有storage，src没有带，上传后显示不出来的问题
        this.props.onChange(this.state.imageFiles.map((file) => { return file.url }))
        if (this.props.singleGraph) {
            this.setState({
                imageFiles: []
            })
        }
    }

    onSegChange = (e) => {
        const index = e.nativeEvent.selectedSegmentIndex
        this.setState({
            multiple: index === 1,
        })
    }

    render() {
        const { imageFiles } = this.state
        let picCount = this.props.picCount
        let imgLength = this.props.imgLength
        if (!picCount) {
            picCount = 1
        }
        console.log("uploadpic", imageFiles)
        return (
            <WingBlank>
                <ImagePicker
                    files={imageFiles}
                    accept="image/*"
                    onChange={this.onChange}
                    onImageClick={(index, fs) => { }}
                    selectable={imageFiles.length < picCount}
                    multiple={false}
                    length={imgLength ? imgLength : 4}
                    disableDelete={this.props.disabled ? true : false}
                    onFail={this.handleOnFail}
                />
            </WingBlank>
        )
    }
}

export default UploadPic
